//
//  ReadCartoonViewController.m
//  A段项目,漫画
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "ReadCartoonViewController.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
enum Direction {
    BEFORE,
    AFTER
};
@interface ReadCartoonViewController ()
@property(nonatomic, retain)UICollectionView *myCollectionView;
@property(nonatomic, retain)NSMutableArray *picArr;
@property(nonatomic, assign)CGFloat picHeight;
//pageViewController
@property(nonatomic, retain)UIPageViewController *myPageViewController;

//中间视图
@property(nonatomic, retain)CenterViewController *myCenterVC;
@property(nonatomic, retain)BeforeViewController *myBeforeVC;
@property(nonatomic, retain)AfterViewController *myAfterVC;
@property(nonatomic, assign)BOOL isChange;
@property(nonatomic, assign)enum Direction direction;
@property(nonatomic, retain)UIActivityIndicatorView *myActivity;
@property(nonatomic, retain)UIView *witeView;
@property(nonatomic, retain)UIImage *myImage;
@property(nonatomic, retain)NSURLResponse *myResponse;
@property(nonatomic, retain)NSMutableData *myData;
@property(nonatomic, retain)UIAlertView *lastAlert;
@property(nonatomic, retain)UIProgressView *myProgress;
@property(nonatomic, retain)NSMutableArray *witeImageArr;
@property(nonatomic, retain)UIImageView *witeImageView;
@property(nonatomic, retain)UILabel *myLabel;
@property(nonatomic, retain)UIView *footView;
@property(nonatomic, assign)BOOL isHidden;
@property(nonatomic, retain)UILabel *indexLabel;
@property(nonatomic, retain)UILabel *countLabel;
@property(nonatomic, retain)UITableView *listTableView;
@property(nonatomic, assign)BOOL isListHidden;
@property(nonatomic, retain)UISlider *lightSlider;
@property(nonatomic, assign)BOOL isNight;
@end
@implementation ReadCartoonViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.picArr = [NSMutableArray array];
        self.witeImageArr = [NSMutableArray array];
        self.isChange = NO;
        self.isHidden = YES;
        self.isListHidden = YES;
        self.isNight = NO;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    [self createAvtivity];
    [self createView];
    [self createData];
    [self createWiteImage];
    [self createFootView];
}

- (void)createWiteImage{
    NSArray *names = @[@"[UU%}~T0FK1XBRSRPT{`2@T－1（被拖移）.tiff", @"[UU%}~T0FK1XBRSRPT{`2@T－2（被拖移）.tiff", @"[UU%}~T0FK1XBRSRPT{`2@T－3（被拖移）.tiff", @"[UU%}~T0FK1XBRSRPT{`2@T－4（被拖移）.tiff", @"[UU%}~T0FK1XBRSRPT{`2@T－5（被拖移）.tiff", @"[UU%}~T0FK1XBRSRPT{`2@T－6（被拖移）.tiff"];
    for (NSString *name in names) {
        UIImage *image = [UIImage imageNamed:name];
        [self.witeImageArr addObject:image];
    }
    self.witeImageView.animationImages = self.witeImageArr;
    //设置播放时间
    self.witeImageView.animationDuration = 0.5;
}

- (void)createAvtivity{
    self.witeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    
    self.witeView.backgroundColor = [UIColor colorWithRed:252 / 255.0 green:188 / 255.0 blue:196 / 255.0 alpha:1];
    [self.view addSubview:self.witeView];
    [self.witeView release];
    CGFloat bili = 225.0 / 300;
    self.witeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3 * 2, WIDTH / 3 * 2 * bili)];
    self.witeImageView.center = CGPointMake(WIDTH / 2, HEIGHT / 3);
    [self.witeView addSubview:self.witeImageView];
    [self.witeImageView release];
    
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3 * 2, 30)];
    self.myLabel.center = CGPointMake(WIDTH / 2, HEIGHT / 3 + WIDTH / 3 * bili + 10 + 20);
    self.myLabel.text = @"粪力加载中!!!!";
    self.myLabel.textAlignment = NSTextAlignmentCenter;
    
    self.myProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    self.myProgress.center = CGPointMake(WIDTH / 2, HEIGHT / 3 + WIDTH / 3 * bili + 10);
    [self.myProgress setProgressViewStyle:UIProgressViewStyleDefault];
    
    
}
- (void)createListTableView{
    //WIDTH / 4    HEIGHT - 270
    //WIDTH / 4   200
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH / 4, HEIGHT - 335, WIDTH / 4, 200)];
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    self.listTableView.backgroundColor = [UIColor whiteColor];
    self.listTableView.alpha = 0.7;
}

//委托协议的方法
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{
    if (completed) {
        //如果完成
        if (self.direction == BEFORE) {
            [self.myBeforeVC.cartoonImage sd_setImageWithURL:[NSURL URLWithString:self.picArr[self.picIndex - 1]]];
            self.picIndex --;
        }else if (self.direction == AFTER){
            [self.myAfterVC.cartoonImage sd_setImageWithURL:[NSURL URLWithString:self.picArr[self.picIndex + 1]]];
            self.picIndex ++;
        }
    }
}

//before
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    self.direction = BEFORE;
    NSLog(@"INDEX    %ld",self.picIndex);
    return self.myBeforeVC;
}
//after
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    self.direction = AFTER;
    NSLog(@"INDEX    %ld",self.picIndex);
    return self.myAfterVC;
}
- (void)createView{
    self.navigationItem.title = self.TiTle;
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(WIDTH, HEIGHT);
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flow];
    [self.view addSubview:self.myCollectionView];
    [self.myCollectionView release];
    [self.myCollectionView registerClass:[PicCartoonCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    self.myCollectionView.pagingEnabled = YES;
    self.myCollectionView.backgroundColor = [UIColor whiteColor];
    
    self.myCollectionView.maximumZoomScale = 2;
    self.myCollectionView.minimumZoomScale = 0.5;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui-5"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-yejianmoshi"] style:UIBarButtonItemStylePlain target:self action:@selector(nightModel:)];
    self.navigationController.navigationBarHidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
    [UIScreen mainScreen].brightness = 0.5;
}
- (void)nightModel:(UIButton *)button{
    if (!self.isNight) {
        [[MidTools shareMidTools].delegate3 modexChangeByNow:NO];
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"iconfont-taiyang"];
        self.isNight = YES;
    }else{
        [[MidTools shareMidTools].delegate3 modexChangeByNow:YES];
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"iconfont-yejianmoshi"];
        self.isNight = NO;
    }
}
- (void)createFootView{
    self.footView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, 100)];
    [self.view addSubview:self.footView];
    [self.footView release];
    self.footView.backgroundColor = [UIColor blackColor];
    self.footView.alpha = 0.7;
    
    self.indexLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 4, 40)];
    [self.footView addSubview:self.indexLabel];
    self.indexLabel.text = [NSString stringWithFormat:@"第 1 页"];
    self.indexLabel.center = CGPointMake(WIDTH / 8 * 3, 50);
    self.indexLabel.tag = 10086;
    self.indexLabel.userInteractionEnabled = YES;
    [self.indexLabel release];
    self.indexLabel.layer.borderWidth = 2;
    self.indexLabel.layer.cornerRadius = 5;
    self.indexLabel.backgroundColor = [UIColor whiteColor];
    self.indexLabel.textAlignment = NSTextAlignmentCenter;
    
    self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 4, 40)];
    [self.footView addSubview:self.countLabel];
    self.countLabel.center = CGPointMake(WIDTH / 8 * 5, 50);
    [self.countLabel release];
    self.countLabel.layer.borderWidth = 2;
    self.countLabel.layer.cornerRadius = 5;
    self.countLabel.backgroundColor = [UIColor whiteColor];
    self.countLabel.textAlignment = NSTextAlignmentCenter;
    [self createListTableView];
    
}

- (void)lightSliderAction:(UISlider *)slider{
    [UIScreen mainScreen].brightness = slider.value;
    NSLog(@"%g",slider.value);
}




//返回方法
- (void)leftButtonAction:(UIButton *)button{
    //先记录浏览记录
    //数据库的操作
    [[DataBaseHandle shareDB] openDB];
    [[DataBaseHandle shareDB] createThroughTable];
    //先把数据接收出来
    NSMutableArray *throughNotesArr = [[DataBaseHandle shareDB] selectThroughNotes];
    BOOL isExit = NO;
    for (throughNotes *tn in throughNotesArr) {
        if ([tn.comic_id isEqualToString:self.comic_id]) {
            isExit = YES;
        }
    }
    if (isExit) {
        //如果存在则更新数据
        [[DataBaseHandle shareDB] upDateCid:self.cid ThroughNotesLastPage:self.picIndex ComicID:self.comic_id];
    }else{
        //如果不存在则插入数据
        [[DataBaseHandle shareDB] insertThroughNotesWithID:self.comic_id Cid:self.cid PicUrl:self.PicUrl TiTle:self.TiTle AndLastPage:self.picIndex];
    }
    NSLog(@"INDEX   %ld",self.picIndex);
    
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.picArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.isHidden) {
        [self.view bringSubviewToFront:self.footView];
    }
    PicCartoonCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    self.picIndex = indexPath.row + 1;
    //定义手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showFootView:)];
    cell.myImageView.userInteractionEnabled = YES;
    [cell.myImageView addGestureRecognizer:tap];
    [tap release];
    
    [cell.myImageView sd_setImageWithURL:self.picArr[indexPath.row] placeholderImage:nil options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        [self.view bringSubviewToFront:self.witeView];
        [self.witeView addSubview:self.myLabel];
        //播放动画
        [self.witeImageView startAnimating];
        [self.view addSubview:self.myProgress];
        self.myProgress.progress = receivedSize / (expectedSize + 0.1) + 0.1;
        NSLog(@"%g",self.myProgress.progress);
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        NSLog(@"图片加载完成");
        [self.witeImageView stopAnimating];
        [self.myProgress removeFromSuperview];
        [self.myLabel removeFromSuperview];
        [self.view bringSubviewToFront:self.myCollectionView];
        if (!self.isHidden) {
            [self.view bringSubviewToFront:self.footView];
            if (!self.isListHidden) {
                [self.view bringSubviewToFront:self.listTableView];
            }
            self.indexLabel.text = [NSString stringWithFormat:@"第 %ld 页",self.picIndex];
        }
        if (image.size.height > HEIGHT) {
            CGFloat bili = image.size.width / (image.size.height + 0.1);
            if (HEIGHT * image.size.width / (image.size.height + 0.1) >= WIDTH) {
                cell.myImageView.frame = CGRectMake(0, 0, WIDTH, WIDTH / bili);
                [cell setImageCenter];
            }else{
                cell.myImageView.frame = CGRectMake(0, 0, HEIGHT * bili, HEIGHT);
                [cell setImageCenter];
            }
            NSLog(@"高 %@",cell.myImageView);
        }else{
            CGFloat bili = image.size.width / (image.size.height + 0.1);
            if (image.size.width >= WIDTH) {
                cell.myImageView.frame = CGRectMake(0, 0, WIDTH, WIDTH / bili);
                [cell setImageCenter];
            }
        }
    }];
    return cell;
}

- (BOOL)prefersStatusBarHidden
{
    if (self.isHidden) {
        //隐藏
        return YES; // 返回NO表示要显示，返回YES将hiden
    }else{
        return NO;
    }
}

//触摸判断
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if (touch.view.tag == 10086) {
        if (self.isListHidden) {
            [UIView animateWithDuration:0.25 animations:^{
                [self.view addSubview:self.listTableView];
            } completion:^(BOOL finished) {
            }];
            self.isListHidden = NO;
        }else{
            [UIView animateWithDuration:0.25 animations:^{
                [self.listTableView removeFromSuperview];
            } completion:^(BOOL finished) {
            }];
            self.isListHidden = YES;
        }
    }
}

- (void)showFootView:(UITapGestureRecognizer *)tap{
    if (self.isHidden) {
        [UIView animateWithDuration:0.25 animations:^{
            self.navigationController.navigationBarHidden = NO;
            [self.view bringSubviewToFront:self.footView];
            
            self.indexLabel.text = [NSString stringWithFormat:@"第 %ld 页",self.picIndex];
            
            self.footView.frame = CGRectMake(0, HEIGHT - 100, WIDTH, 100);
            self.isHidden = NO;
            [self.view bringSubviewToFront:self.listTableView];
            [self prefersStatusBarHidden];
        } completion:^(BOOL finished) {
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.navigationController.navigationBarHidden = YES;
            [self.view bringSubviewToFront:self.myCollectionView];
            self.footView.frame = CGRectMake(0, HEIGHT, WIDTH, 100);
            self.isHidden = YES;
            if (!self.isListHidden) {
                [self.listTableView removeFromSuperview];
            }
            [self prefersStatusBarHidden];
        } completion:^(BOOL finished) {
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.picArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuse = @"reuse";
    ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[ListTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse] autorelease];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.indexLabel.text = [NSString stringWithFormat:@"第 %ld 页",indexPath.row + 1];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [UIView animateWithDuration:0.25 animations:^{
        self.myCollectionView.contentOffset = CGPointMake(WIDTH * indexPath.row, 0);
    } completion:^(BOOL finished) {
    }];
}


- (void)createData{
    NSString *picSTR = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListForIos/comic_id/%@/cid/%@/clientType/0",self.comic_id, self.cid];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:picSTR parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableDictionary *dataDic = dic[@"data"];
        NSMutableArray *img_infosArr = dataDic[@"img_infos"];
        for (NSMutableDictionary *d in img_infosArr) {
            NSString *picURL = d[@"current_img_url"];
            [self.picArr addObject:picURL];
        }
        NSLog(@"COUNT  %ld",self.picArr.count);
        NSLog(@"数据请求成功");
        self.countLabel.text = [NSString stringWithFormat:@"共 %ld 页",self.picArr.count];
        //根据浏览记录设置偏移量
        self.myCollectionView.contentOffset = CGPointMake(WIDTH * (self.picIndex - 1), 0);
        [self.listTableView reloadData];
        [self.myCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"数据请求失败");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
